﻿using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.IO;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.IO;

using GHIElectronics.NETMF.Hardware;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.IO;
using GHIElectronics.NETMF.System;

using FezPanda_SDCardTester;
using CameraController;

namespace CameraController
{
    public class CameraController
    {
        public static void Main()
        {
            PersistentStorage sdPS = new PersistentStorage("SD");
            sdPS.MountFileSystem();

            bool ledState = false;
            OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED,ledState);

            Debug.EnableGCMessages(false);

            using (var camera = new LinkspriteCamera(new SerialPort("COM1", 38400, Parity.None, 8, StopBits.One)))
            {
                //DoSuccessFail(camera.Reset, "Reset successfull", "ERROR resetting");
                //DoSuccessFail(() => camera.SetPictureSize(LinkspriteCamera.SET_SIZE_640x480), "Size change successfull", "ERROR changing size");
                //DoSuccessFail(camera.Reset, "Reset successfull", "ERROR resetting");

                if (!camera.SetPictureSize(SET_SIZE_160x120))
                    Debug.Print("Size change failed!");

                //if (!camera.Init_115200())
                //    Debug.Print("Baud change failed!");

                if (File.Exists(@"\SD\test.jpeg"))
                {
                    File.Delete(@"\SD\test.jpeg");
                }
            
                Debug.Print("Reseting...");
                if (camera.Reset())
                {
                    
                    Debug.Print("Writing...");
                    DateTime startTime = DateTime.Now;
                    led.Write(true);
                    Debug.Print("Led check");
                    camera.GetPicture(ProcessChunk);
                    Debug.Print("LED check");
                    led.Write(false);
                    DateTime endTime = DateTime.Now;

                    TimeSpan timeTaken = endTime - startTime;
                    Debug.Print("Time : " + timeTaken.ToString());
                }

                DoSuccessFail(camera.Stop, "Stop successful", "ERROR stopping");
            }  

            //SDCardModule.WriteTesttoSD();

            sdPS.UnmountFileSystem();

			Debug.Print("Unmounted");
        }


        private static void ProcessChunk(byte[] bytes)
        {
            
            SDCardModule.WriteJPEGtoSD(bytes);

            //  foreach (var byter in bytes)
            //      Debug.Print(byter.ToString());
        }

        private delegate bool FuncBool();

        private static void DoSuccessFail(FuncBool action, string success, string fail)
        {
            if (action())
                Debug.Print(success);
            else
                Debug.Print(fail);
        }

        public static readonly byte[] SET_SIZE_160x120 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x22 };
        public static readonly byte[] SET_SIZE_320x240 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x11 };
        public static readonly byte[] SET_SIZE_640x480 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x00 };
    }
}
    
//This just returns the bytes over the debug cable, you can do something with the bytes if you 
//have an SD card or are going to transmit, otherwise just copy the bytes to the clippboard 
//from the output window and use the below snippet to create the jpg file and look at it on your computer:

            //var byteString = @"<put bytes here>";
            //var lines = byteString.Split(Environment.NewLine.ToCharArray());
            //var bytes = new List<byte>();
            //foreach (var line in lines.Where(x => (x ?? "").Trim() != ""))
            //{
            //    byte num = Convert.ToByte(line);
            //    bytes.Add(num);
            //}

            //string file = @"C:\temp.jpg";
            //File.WriteAllBytes(file, bytes.ToArray());
            //System.Diagnostics.Process.Start(file);
